<?php
class video extends Model{
	public static function getTableName(){
		return 'video';
	}

	/*
	 * by donald
	 * at 2011-10-27
	 */
	public function set($object)
	{
		$this->programme_id = $object->programme_id;
		$this->vi_id = $object->vi_id;
		$this->vi_status = $object->vi_status;
		$this->ii_id = $object->ii_id;
		$this->ii_status = $object->ii_status;
		$this->video_params = $object->video_params;
		$this->thumbnail_url = $object->thumbnail_url;
		$this->image_source_url = $object->image_source_url;
		$this->source_url = $object->source_url;
		$this->other_videos = $object->other_videos;
		$this->first_time_onair = $object->first_time_onair;
		$this->highlighted_cast_roles = $object->highlighted_cast_roles;
		$this->casts = $object->casts;
		$this->available_tag_types = $object->available_tag_types;
		$this->tags = $object->tags;
		$this->folders = $object->folders;
		$this->country_allow_list = $object->country_allow_list;
		$this->country_deny_list = $object->country_deny_list;
		$this->publish_datetime = $object->publish_datetime;
		$this->expire_datetime = $object->expire_datetime;
		$this->copyright = $object->copyright;
		$this->mdes_status = $object->mdes_status;
		$this->status = $object->status;
		$this->premium_flag = $object->premium_flag;
		$this->video_type = $object->video_type;
		$this->created_at = $object->created_at;
		$this->created_by = $object->created_by;
		$this->modified_at = $object->modified_at;
		$this->modified_by = $object->modified_by;
	}

	public function getResultList($findRelation, $field, $operation, $value, $start, $length, $sidx	= NULL, $sord = NULL, $unpublish = 0)/*{{{*/
	{
		$find	=	$findRelation['mapField'];
		$db_con = ($unpublish == 1) ? CommonUtils::getDbConn(0,'preview') : Model::$dbo['r'];
        # first, deal with title party!
        $titleWhere =   $programmeTitleIds  =   NULL;
        $pathWhere  =   NULL;
        $videoWhere =   NULL;
        $searchSing =   FALSE;
        $programmes =   array();
		$where      =   array();
        $resField   =   $resOperation   =   $resValue   =   array();
        $folder_videos = $videos = array();

        foreach ($field as  $fieldKey=>$fieldValue) {
            switch ($fieldValue) {
                case 'title':
                    $titleWhere[] = Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                    break;
                case 'path':
                    $pathWhere[] = Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                    break;
                case 'video_title':
                    $videoWhere[] = Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                    break;
                case 'folder_id':
                    $folder_video_new = folder_item::getItemByFolderId($value[$fieldKey]);
                    $folder_videos = array_merge($folder_videos, $folder_video_new); 
                    break;
                case 'premium':
                    if ($value[$fieldKey] != '2') { // 2=all
                        $resField[$fieldKey] = $fieldValue;
                        $resOperation[$fieldKey] = $operation[$fieldKey];
                        $resValue[$fieldKey] = $value[$fieldKey];
                    }
                    break;
                case 'premium_items':
                    if (isset($value[$fieldKey]) && is_array($value[$fieldKey])) {
                        foreach ($value[$fieldKey] as $_value) {
                            if ($_value == 'subscription_flag') {
                                $where_extra[] = '`subscription_flag`=1';
                            } else if ($_value == 'ppv_flag') {
                                $where_extra[] = '`ppv_flag`=1';
                            }
                        }
                    }
                    break;
                case 'video_type':
                    if ($value[$fieldKey] != 'all') { // 2=all
                        $resField[$fieldKey] = $fieldValue;
                        $resOperation[$fieldKey] = $operation[$fieldKey];
                        $resValue[$fieldKey] = $value[$fieldKey];
                    }
                    break;
                default:
                    $resField[$fieldKey] = $fieldValue;
                    $resOperation[$fieldKey] = $operation[$fieldKey];
                    $resValue[$fieldKey] = $value[$fieldKey];
            }
        }

        if (!empty($titleWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByTitle($titleWhere,$field,$operation);
        }

        if (!empty($pathWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByPath($pathWhere);
        }

        if (!empty($videoWhere)) {
            $videos = CommonUtils::getMediaIdsByTitle('video',$videoWhere,$field,$operation);
            if (empty($videos)) {
                $where[] = 'id IS NULL';
            }
        }
            
        #where:video_id
        if (!empty($videos) && !empty($folder_videos)) {
            $all_video = array_intersect($videos, $folder_videos);
            if (!empty($all_video)) {
                $where[] = "id IN (" . implode(',', $all_video) . ")";
            } else {
                $where[] = 'id IS NULL';
            }
        } else if (!empty($videos)) {
		    $where[] = 'id in('. implode(',',$videos) .')';
        } else if (!empty($folder_videos)) {
            $where[] = "id in (" . implode(',', $folder_videos) . ")";
        } else if (array_search('folder_id', $field) !== FALSE) {
            $where[] = 'id IS NULL';
        }

        if ($searchSing)
        {
			if (count($programmes)>1){
				$programmes = call_user_func_array('array_intersect',$programmes);
			}else{
				$programmes = $programmes[0];
			}
			$programmeTitleIds = implode(',', $programmes);   
            if (empty($programmeTitleIds))  $programmeTitleIds  =   '""';
            $programmeTitleIds  =   ' WHERE video.programme_id IN ('. $programmeTitleIds. ')';
        }

		$where[] =	Model::assembleWhereSentence($find, $resField, $resOperation, $resValue);
		$where   = array_filter($where);

		if (!empty($where)) {
            $where	=	' WHERE '. implode(' and ',$where);
		}else{
			$where = ' WHERE 1';
		}

        if (!empty($where_extra)) {
            $where .= ' AND ' . implode(' AND ', $where_extra);
        }

		$subSql =	'
			SELECT
				video.id AS	id,
                video.programme_id AS  programme_id,
				(
					SELECT
						GROUP_CONCAT(`programme-language`.title SEPARATOR "\n\t")
					FROM
						video AS inVideo LEFT JOIN `programme-language` ON (inVideo.programme_id = `programme-language`.programme_id)
					WHERE
						inVideo.id = video.id
				) AS	title,
                IFNULL((
                    SELECT
                        onair_episode_no
                    FROM
                        episode AS e, `episode-video` AS ev, video as v
                    WHERE
                        e.id = ev.episode_id
                        AND ev.video_id = v.id
                        AND v.id =  video.id
                        AND onair_episode_no is not null
                    GROUP BY ev.video_id
                ),"") AS  onair_episode_no,
				(
					SELECT
						GROUP_CONCAT(`video-language`.title SEPARATOR "\n\t")
					FROM
						video AS inVideo LEFT JOIN `video-language` ON (inVideo.id = `video-language`.video_id)
					WHERE
						inVideo.id = video.id
				) AS	video_title,
				video.status AS	record_status,
				video.modified_at,
				video.modified_by AS	modified_by,
                `programme`.premium_flag AS premium,
                `video`.`video_type`,
                `video_premium`.ppv_flag,
                `video_premium`.subscription_flag
			FROM video
            LEFT JOIN `video_premium` ON (`video_premium`.video_id = `video`.id)
            LEFT JOIN `programme` ON (`video`.programme_id = `programme`.id)
            '. $programmeTitleIds. '
			GROUP BY id
			';

		$sql=	'
			SELECT
				id,
                programme_id,
				title,
                onair_episode_no,
                video_title,
				record_status,
				modified_at,
				modified_by
			FROM
			(
				'. $subSql. '
			)	AS	findApi
			'.	$where;

		# Order By ...
		$orderBy=	$orderTmp   =   NULL;
		if (!empty($sidx)	&&	!empty($find[$sidx]))
		{
			$orderTmp	=	$find[$sidx];
			if ('desc'	==	$sord)
			{
				$orderTmp	.=	' DESC ';
			}
			elseif ('asc'	==	$sord)
			{
				$orderTmp	.=	' ASC ';
            }
            $orderBy[]  =   $orderTmp;
		}

        if (!empty($where))
        {
            foreach ($field as  $value)
            {
                if (empty($find[$value]))   continue;
                if ('path'  ==  $value)     continue;
                $orderBy[]  =   $find[$value];
            }
        }

        if (empty($orderBy))    $orderBy[]  =   '`findApi`.`modified_at` DESC';

        $orderBy    =   ' ORDER BY '. implode(', ', $orderBy);
		$dataSql	=	$sql. $orderBy. ' LIMIT '. $start. ', '. $length;
		$totalSql	=	'SELECT count(*) AS num FROM ('. $sql. ')	AS	tmp';

		$result	=	$db_con->findBySql(__class__,$dataSql);
		$retAll	=	$db_con->findBySql(__class__,$totalSql);

        if (empty($retAll[0]->num)) $retAll[0]->num =   0;
        if (empty($result[0]))      $result         =   array();
		$list	=	array();
		$list['page']	=	ceil($start / $length) + 1;
		$list['total']	=	ceil($retAll[0]->num / $length);
		$list['records']=	$retAll[0]->num;

		foreach	($result	as	$gridData)
		{
			$tmp			=	array();
			$tmp['id']		=	$gridData->id;
			$tmp['cell']	=	array();

			$gridData->title    = explode("\n\t",$gridData->title);
			$gridData->title[0] = htmlentities($gridData->title[0],ENT_QUOTES,'UTF-8');
			$gridData->title[1] = isset($gridData->title[1]) ? htmlentities($gridData->title[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->title    = implode('<br />',$gridData->title);

			$gridData->video_title    = explode("\n\t",$gridData->video_title);
			$gridData->video_title[0] = htmlentities($gridData->video_title[0],ENT_QUOTES,'UTF-8');
			$gridData->video_title[1] = isset($gridData->video_title[1]) ? htmlentities($gridData->video_title[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->video_title    = implode('<br />',$gridData->video_title);

			$gridData->modified_at= str_replace(' ','<br />',$gridData->modified_at);

            $originalStatus =   $gridData->record_status;
            if (!empty($unpublish))
            {
                $publish_log = publish_log::getPublishLog(__class__, $gridData->id);
                if (property_exists($publish_log, 'non_premium')) {
                    $publish = Model::object2array($publish_log->non_premium); 
                } else {
                    $publish = array();
                }

                $gridData->record_status    =   NULL;
                $gridData->modified_by      =   NULL;
                $gridData->modified_at      =   NULL;
                if (isset($publish['action'])   &&  isset(AC::$publicLogAction[$publish['action']]))
                {
                    $gridData->record_status    =   AC::$publicLogAction[$publish['action']];
                    isset($publish['published_by']) &&  $gridData->modified_by  =   $publish['published_by'];
                    isset($publish['published_at']) &&  $gridData->modified_at  =   $publish['published_at'];
                }
            }
            else
            {
                isset(AC::$op_status[$gridData->record_status]) &&  $gridData->record_status    =   AC::$op_status[$gridData->record_status];
            }

			foreach ($find	as	$name	=>	$column) {
                switch ($name) {
                case 'programme_id':
                case 'path':
                case 'premium':
                case 'premium_items':
                case 'video_type':
                    break;
                default:
                    $tmp['cell'][]	=	$gridData->$name;
                    break;
                }
			}

            $delEdit    =   $delView    =   NULL;
            if (AC::STATUS_DELETED !=   $originalStatus &&  empty($unpublish))
            {
                $delEdit    =   '<a title="Edit" href="get_video.html?act=edit&id='. $gridData->id. '" class="btn edit shortBtn videoEditBtn ui-state-default ui-corner-all"><span class="ui-icon ui-icon-pencil"/>Edit</a>';
            }
            if (empty($unpublish)   ||  (isset($publish['action'])  &&  AC::LOG_OP_PUBLISH  ==  $publish['action']))
            {
                $delView    =   '<a title="View" href="get_video.html?act=view&id='. $gridData->id. '&unpublish='. $unpublish. '" class="btn view shortBtn ui-state-default ui-corner-all"><span class="ui-icon ui-icon-image"/>View</a>';
            }
            $actionButtons	=	$delEdit. $delView;

            /*
            if ($this->getRelation($gridData->id) &&    empty($unpublish))
            {
                $actionButtons  .=  '
                    <span class="btn view ui-state-default ui-corner-all longBtn"><span class="txt">Chapter Marking</span>';
                if (AC::STATUS_DELETED !=   $originalStatus)
                    $actionButtons  .=  '<a class="btn edit" title="Edit" href="get_chapter.html?act=edit&type=chapter_marking&vid='. $gridData->id. '" title="Edit Chapter Marking"><span class="ui-icon ui-icon-pencil"/></a>';
                $actionButtons  .=  '<a class="btn view" title="View" href="get_chapter.html?act=view&type=chapter_marking&vid='. $gridData->id. '" title="View Chapter Marking"><span class="ui-icon ui-icon-image"/></a>
                    </span>
                    ';
            }
             */
            $tmp['cell'][]	=	$actionButtons;
			$list['rows'][]	=	$tmp;
            unset($publish);
		}

		return	$list;
	}/*}}}*/

    public function getRelation($id)/*{{{*/
    {
        $totalSql   =   'SELECT COUNT(*) AS num FROM `episode-video` WHERE video_id = "'. $id. '"';
        $retAll	    =	Model::$dbo['r']->findBySql(__class__,$totalSql);
        if ($retAll[0]->num > 0)    return  TRUE;
        else    return  FALSE;
    }/*}}}*/

	public function getDetails($id)/*{{{*/
	{
        $sql=   '
            SELECT
                video.*,
                GROUP_CONCAT(`programme-language`.title SEPARATOR "\n\t")     AS  programme,
                `video-language`.title  AS  title,
                `video-language`.description    AS  description
            FROM
                video LEFT JOIN `video-language` ON (video.id = `video-language`.video_id)
                LEFT JOIN `programme-language` ON (video.programme_id = `programme-language`.programme_id)
            WHERE
                video.id = '.$id.'
			GROUP BY video.id
            ';
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);
        $sql = "SELECT * FROM `video-language` WHERE video_id = " . $id;
        $ro = Model::$dbo['r']->findBySql(__class__, $sql);
        $video_language = array();
        foreach ($ro as $obj) {
            $video_language[$obj->language_id] = $obj;
			
			if (!isset($video_language[2])) {
				foreach ($obj as $key=>$value) {
					$video_language[2][$key] = '';
				}
			}
        }

        $ret[0]->video_language = $video_language;
        if(isset($ret[0]) && !empty($ret[0]))
        {
            if('ALL' == $ret[0]->country_deny_list)
            {
                $ret[0]->country_allow_list = ParseCountryCode::country2json(AC::COUNTRY_LIST_CODE,$ret[0]->country_allow_list,0);
            }
            else
            {
                $ret[0]->country_deny_list = ParseCountryCode::country2json(AC::COUNTRY_LIST_CODE,$ret[0]->country_deny_list,1);
            }
        }
        return isset($ret[0]) ? Model::object2array($ret[0]) : false;
    }/*}}}*/

    /**
     * get proofread SQL
     * @param   $id Int
     * @return  Array
     */
    public function getProofread($id,$premium=false)/*{{{*/
    {
        if (empty($id)) return  array();
        $sqlArr =   array(
                    'video'             =>  array('id = "'. $id. '"','vi_status = 1'),
                    'video-language'    =>  array('video_id = "'. $id. '"'),
                    'video_export'      =>  array('video_id = "'. $id. '"'),
                    'episode-video'     =>  array('video_id = "'. $id. '"'),
                );
		if($premium){
			$sqlArr['video']              = array('id = "'. $id. '"','premium_flag = 1','vi_status = 1');
			$sqlArr['video_premium']      = array('video_id = "'.$id.'"');
			$sqlArr['video_ppv']          = array('video_id = "'.$id.'"');
			$sqlArr['video_subscription'] = array('video_id = "'.$id.'"');
		}

        $sqlArray   =   array();
        foreach ($sqlArr    as  $tableName  =>  $whereArray)
        {
            $sqlArray[$tableName]   =   Model::assembleGetProofreadSql($tableName, $whereArray);
        }
        return  $sqlArray;
    }/*}}}*/

	/*
	 * by donald
	 * at 2011-10-25
	 */
    public function getClone($id)
    {
        if (empty($id)) return  array();

        $sqlArr = array(
			'video' => array('id = "'. $id. '"','vi_status = 1'),
			'video-language' => array('video_id = "'. $id. '"'),
			'video_export' => array('video_id = "'. $id. '"'),
			'episode-video' => array('video_id = "'. $id. '"'),
			'video_premium' => array('video_id = "'.$id.'"'),
			'video_ppv' => array('video_id = "'.$id.'"'),
			'video_subscription' => array('video_id = "'.$id.'"'),
		);

        $sqlArray = array();
        foreach ($sqlArr as $tableName => $whereArray) {
            $sqlArray[$tableName] = Model::assembleGetProofreadSql($tableName, $whereArray);
        }
        return  $sqlArray;
    }

    /*
     * @param $video_id INT
     * @return TRUE | FALSE
     * bug 849
     */
    static function check_video_publish_status($video_id) {/*{{{*/
        $sql = "
            SELECT status
            FROM publish_log
            WHERE item_type_id = 52 
                AND item_id = " . $video_id . " 
            ORDER BY published_at DESC
            LIMIT 1";
        $obj = Model::$dbo['r']->findBySql(__CLASS__, $sql);
        $dataArray = Model::object2array($obj);
        return ($dataArray[0]['status'] == AC::STATUS_PUBLISH) ? TRUE : FALSE;
    }/*}}}*/

    /*
     * get video info
     */
    static function get_video_info($video_id) {/*{{{*/
        $sql = "SELECT * FROM `video` WHERE `id` = " . $video_id;
        $data = Model::selectBySql($sql);
        return $data[0];
    }/*}}}*/


    public static function get_waiting_video()
    {
         $sql = "
             SELECT id, status, created_at, created_by, modified_at, modified_by 
             FROM video WHERE vi_status = ".AC::VIDEO_STATUS_WAITING ;
        $data = Model::selectBySql($sql);
        $mails = array();
        if($data)
        {
            foreach($data as $row)
            {
                $mail = array();
                $hour = floor( (time() - strtotime( $row['modified_at'])) / (60*60) );
                if( $hour > 2 )
                {
                    $mail['id'] = $row['id'];
                    $mail['modified_by'] = $row['modified_by'] ;
                    $mails[] = $mail;
                }
            }
        }
        return $mails;
    }

	public static function checkVideosUploadedSuccess(array $video_ids)
	{
		$sql = '
			SELECT COUNT(*) AS total FROM video 
			WHERE id IN (' . implode(',', $video_ids) . ') AND 
				vi_status <> ' . AC::VIDEO_STATUS_UPLOADED . '
			';
		$rs = Model::selectBySql($sql);
		return empty($rs[0]['total']) ? TRUE : FALSE;
	}

	/*
	 * by donald
	 */
	public function add_change_log($programme_id)
	{
		$field['type'] = $this->getTableName();
		$field['keys'] = array('id' => $this->id);
		$field['is_active'] = 1;
		$field['programme_id'] = $programme_id;
		$field['episode_id'] = 0;
		$field['is_publish'] = 0;

		change_log::updateOne($field);
	}

	/*
	 * by donald
	 */
	public function delete_change_log()
	{
		$type = $this->getTableName();
		$keys = array('id' => $this->id);
		$is_publish = 0;

		change_log::delTypeAndKeysLog($type, $keys, $is_publish);
	}

}
